import 'package:flutter/cupertino.dart';

final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();


/// 公共文件
abstract class LifecycleAwareState<T extends StatefulWidget> extends State<T> with WidgetsBindingObserver, RouteAware {
  bool _isSubscribed = false;
  bool isResumed = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    if (!_isSubscribed) {
      final ModalRoute? modalRoute = ModalRoute.of(context);
      if (modalRoute is PageRoute) {
        routeObserver.subscribe(this, modalRoute);
        _isSubscribed = true;
      }
    }
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.paused) {
      _pause();
    } else if (state == AppLifecycleState.resumed) {
      _resume();
    }
  }

  @override
  void didPush() {
    _resume();
  }

  @override
  void didPop() {
    _pause();
  }

  @override
  void didPopNext() {
    _resume();
  }

  @override
  void didPushNext() {
    _pause();
  }

  void _pause() {
    if (isResumed) {
      isResumed = false;
      pause();
    }
  }

  void _resume() {
    if (!isResumed) {
      isResumed = true;
      resume();
    }
  }

  @protected
  void pause() {}

  @protected
  void resume() {}
}
